package com.banciyuan.bcywebview.biz.detail.complex;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.DetailDataHelper;
import com.banciyuan.bcywebview.biz.detail.complex.holder.ChargeHolder;
import com.banciyuan.bcywebview.biz.detail.complex.holder.CommentBottomHolder;
import com.banciyuan.bcywebview.biz.detail.complex.holder.CommentHolder;
import com.banciyuan.bcywebview.biz.detail.complex.holder.HeaderHolder;
import com.banciyuan.bcywebview.biz.detail.complex.holder.ImageHolder;
import com.banciyuan.bcywebview.biz.detail.complex.holder.InfoHolder;
import com.banciyuan.bcywebview.biz.detail.complex.holder.VideoHeaderHolder;
import com.banciyuan.bcywebview.biz.detail.complex.holder.WorkAcgHolder;
import com.banciyuan.bcywebview.biz.detail.image.SplitTask;
import com.banciyuan.bcywebview.biz.detail.post.PostHeaderHolder;
import com.banciyuan.bcywebview.biz.picshow.ViewPictureActivity2;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.GifLoader;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.core.assist.FailReason;
import com.banciyuan.bcywebview.utils.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.Complex;
import de.greenrobot.daoexample.model.DetailComment;
import de.greenrobot.daoexample.model.DetailImageData;
import de.greenrobot.daoexample.model.DetailType;
import de.greenrobot.daoexample.model.Multi;

/**
 * Created by squall on 2016/8/10.
 */
public class ComplexAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context mContext;
    private Complex mItem;
    private Map<String, DetailImageData> mMapItems = new HashMap<>();
    private HashMap<String, AsyncTask<Void, Void, List<DetailImageData>>> mTask = new HashMap<>();
    private List<DetailImageData> ilist = new ArrayList<>();
    private List<DetailComment> dlist = new ArrayList<>();
    private List<String> images = new ArrayList<>();
    private ImageSplitListener imageSplitListener;
    private DetailType detailType;

    private final static int HEADER = 0;
    private final static int INTRO = 1;
    private final static int IMAGE = 2;
    private final static int CHARGE = 3;
    private final static int WORK = 4;
    private final static int COMMENT = 5;
    private final static int COMMENT_BOTTOM = 6;
    private boolean onBind;

    private LayoutInflater inflater;
    private ImageLoader imageLoader;
    private GifLoader gifLoader;

    public ComplexAdapter(Context mContext, Complex mItem, DetailType detailType, List<DetailComment> comments) {
        this.mItem = mItem;
        this.dlist = comments;
        this.mContext = mContext;
        this.inflater = LayoutInflater.from(mContext);
        this.imageLoader = ImageLoader.getInstance();
        this.gifLoader = new GifLoader();
        this.imageSplitListener = new ImageSplitListener();
        this.detailType = detailType;
        this.mItem.setTimelineType(detailType.getTimelineType());
        setImage();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case HEADER:
                if (detailType.getTimelineType() != TimelineFactory.TIMELINE_TYPE_GROUP) {
                    if (StringUtil.notNullEqual(mItem.getType(), "svideo")) {
                        return new VideoHeaderHolder(inflater.inflate(R.layout.video_detail_head, null));
                    } else {
                        return new HeaderHolder(inflater.inflate(R.layout.detail_firstheader, null));
                    }
                } else {
                    return new PostHeaderHolder(inflater.inflate(R.layout.post_detail_head, null));
                }
            case INTRO:
                return new InfoHolder(inflater.inflate(R.layout.detail_header_layout, parent, false));
            case IMAGE:
                return new ImageHolder(inflater.inflate(R.layout.detail_list_item, null));
            case CHARGE:
                return new ChargeHolder(inflater.inflate(R.layout.charge_detail_item, parent, false));
            case WORK:
                return new WorkAcgHolder(inflater.inflate(R.layout.comment_line_layout, null), mContext, detailType.getTimelineType());
            case COMMENT_BOTTOM:
                return new CommentBottomHolder(inflater.inflate(R.layout.comment_bottom_layout, null));
            default:
                return new CommentHolder(inflater.inflate(R.layout.comment_detail_item, null), mItem.getUid());
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        onBind = true;
        switch (getItemViewType(position)) {
            case HEADER:
                if (detailType.getTimelineType() != TimelineFactory.TIMELINE_TYPE_GROUP) {
                    if (StringUtil.notNullEqual(mItem.getType(), "svideo")) {
                        VideoHeaderHolder videoHeaderHolder = (VideoHeaderHolder) holder;
                        videoHeaderHolder.setData(mItem, mContext);
                    } else {
                        HeaderHolder headerHolder = (HeaderHolder) holder;
                        headerHolder.setData(mItem, mContext);
                    }
                } else {
                    PostHeaderHolder postHolder = (PostHeaderHolder) holder;
                    postHolder.setData(mItem, mContext);
                }
                break;
            case INTRO:
                InfoHolder infoHolder = (InfoHolder) holder;
                if (detailType.getTimelineType() != TimelineFactory.TIMELINE_TYPE_GROUP) {
                    if (StringUtil.notNullEqual(mItem.getType(), "svideo")) {
                        infoHolder.setGone();
                    } else {
                        infoHolder.setData(mItem, mContext);
                    }
                } else {
                    infoHolder.setGone();
                }
                break;
            case IMAGE:
                ImageHolder image = (ImageHolder) holder;
                processImageType(image, position);
                break;
            case CHARGE:
                ChargeHolder chargeHolder = (ChargeHolder) holder;
                chargeHolder.setData(mItem, mContext);
                break;
            case WORK:
                WorkAcgHolder workHolder = (WorkAcgHolder) holder;
                workHolder.setData(mItem, detailType.getTimelineType());
                break;
            case COMMENT_BOTTOM:
                CommentBottomHolder bottom = (CommentBottomHolder) holder;
                bottom.setData(mItem);
                break;
            default:
                int index = position - 4 - ilist.size();
                CommentHolder commentHolder = (CommentHolder) holder;
                commentHolder.setData(index, dlist.get(index), mContext, true, detailType, false);
                break;
        }
        onBind = false;
    }

    private void processImageType(ImageHolder image, int position) {
        int index = position - 2;
        final DetailImageData item = ilist.get(index);
        int status = item.getStatus();
        if (item.isIf_size()) {
            ViewGroup.LayoutParams mParams = image.img_iv.getLayoutParams();
            mParams.height = item.getHeight();
            image.img_iv.setLayoutParams(mParams);
        }

        if (!item.getUrl().contains(".gif") && !StringUtil.notNullEqual(item.getType(), "gif")) {
            image.gif_iv.setVisibility(View.GONE);
            image.img_iv.setVisibility(View.VISIBLE);
        } else {
            image.gif_iv.setVisibility(View.VISIBLE);
            image.img_iv.setVisibility(View.GONE);
        }
        if (!item.is_padding()) {
            ((View) image.img_iv.getParent()).setPadding(0, 0, 0, 0);
        } else {
            ((View) image.img_iv.getParent()).setPadding(0, UIUtils.dip2px(4, mContext), 0, 0);
        }

        switch (status) {
            case DetailImageData.DOWNLOAD_ERROR:
                image.img_iv.setImageDrawable(mContext.getResources().getDrawable(R.drawable.loading_error));
                break;
            case DetailImageData.DOWNLOAD_UNSTART:
                image.img_iv.setImageDrawable(mContext.getResources().getDrawable(R.drawable.loading));
                if (!item.getUrl().contains(".gif")) {
                    imageLoader.loadImage(item.getUrl(), null, ImageOptions.optionsCopy, imageSplitListener, null, true);
                } else {
                    item.onLoadingComplete();
                    try {
                        gifLoader.displayGif(item.getUrl(), image.gif_iv);
                    } catch (OutOfMemoryError e) {
                        e.printStackTrace();
                    }
                }
                break;
            case DetailImageData.DOWNLOAD_ING:
                image.img_iv.setImageDrawable(mContext.getResources().getDrawable(R.drawable.loading));
                break;
            case DetailImageData.DOWNLOAD_COMPLETE:
                image.img_iv.setImageDrawable(mContext.getResources().getDrawable(R.drawable.loading));
                if (!item.getUrl().contains(".gif") && !StringUtil.notNullEqual(item.getType(), "gif")) {
                    imageLoader.displayImage(item.getUrl(), image.img_iv, ImageOptions.optionsDetail, new SimpleImageLoadingListener() {
                        @Override
                        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                            item.beforeLoading();
                        }
                    }, null, true);
                } else {
                    try {
                        gifLoader.displayGif(item.getUrl(), image.gif_iv);
                    } catch (OutOfMemoryError e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                image.img_iv.setImageDrawable(mContext.getResources().getDrawable(R.drawable.loading));
                break;
        }

        View.OnClickListener imageListener = new OnImageClick(item, item.getSub_index());
        image.img_iv.setOnClickListener(imageListener);
        image.gif_iv.setOnClickListener(imageListener);
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return HEADER;
        } else if (position == 1) {
            return INTRO;
        } else if (position > 1 && position < ilist.size() + 2) {
            return IMAGE;
        } else if (position == ilist.size() + 2) {
            return CHARGE;
        } else if (position == ilist.size() + 3) {
            return WORK;
        } else if (position > ilist.size() + 3 && position <= ilist.size() + 3 + dlist.size()) {
            return COMMENT;
        } else {
            return COMMENT_BOTTOM;
        }
    }

    @Override
    public int getItemCount() {
        if (mItem.getStatus() == 1) {
            if (mItem.getLock() != null) {
                return 1;
            } else {
                return ilist.size() + dlist.size() + 5;
            }
        } else {
            return 1;
        }
    }

    private void setImage() {
        for (int i = 0; i < mItem.getMulti().size(); i++) {
            Multi m = mItem.getMulti().get(i);
            if (m.getType().equals("image")) {
                DetailImageData imageData = new DetailImageData(m.getPath());
                imageData.setLocation(i);
                imageData.setSub_index(i);
                mMapItems.put(m.getPath(), imageData);
                ilist.add(imageData);
                images.add(m.getPath());
            }
        }
    }

    private class OnImageClick implements View.OnClickListener {

        DetailImageData mData;
        int position;

        public OnImageClick(DetailImageData mData, int position) {
            this.mData = mData;
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            if (mData.getStatus() == DetailImageData.DOWNLOAD_COMPLETE) {
                Intent intent = new Intent(mContext, ViewPictureActivity2.class);
                intent.putStringArrayListExtra("imageUrls", (ArrayList<String>) images);
                intent.putExtra("position", position);
                intent.putExtra("Forbidden_right_click", mItem.getProperties().isForbidden_right_click());
                intent.putExtra("water_mark", mItem.getProperties().isWater_mark());
                DetailDataHelper.putBaseDetailValue(intent, DetailDataHelper.gotoViewPic(mItem));
                mContext.startActivity(intent);
            } else if (mData.getStatus() == DetailImageData.DOWNLOAD_ERROR) {
                mData.setStatus(DetailImageData.DOWNLOAD_UNSTART);
                notifyItemChanged(mData.getLocation() + 2);
                imageLoader.loadImage(mData.getUrl(), null, ImageOptions.options, imageSplitListener, null, true);
            }
        }
    }

    private class afterDownloadTask extends AsyncTask<Void, Void, List<DetailImageData>> {

        private DetailImageData item;
        private File mfile;

        afterDownloadTask(DetailImageData item, File mfile) {
            this.item = item;
            this.mfile = mfile;
        }

        @Override
        protected List<DetailImageData> doInBackground(Void... p) {
            try {
                SplitTask splitTask = new SplitTask(item, mfile, mContext);
                return splitTask.split();
            } catch (OutOfMemoryError e) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(List<DetailImageData> dlist) {
            if (!onBind && dlist != null) {
                if (dlist.size() > 1) {
                    for (int i = 0; i < ilist.size(); i++) {
                        if (ilist.get(i).getUrl().equals(dlist.get(0).getOrgin_url())) {
                            ilist.remove(i);
                            ilist.addAll(i, dlist);
                        }
                    }
                    for (int i = 0; i < ilist.size(); i++) {
                        ilist.get(i).setLocation(i);
                    }
                    notifyItemChanged(dlist.get(0).getLocation() + 2);
                    notifyItemRangeInserted(dlist.get(0).getLocation() + 3, dlist.size() - 1);
                } else if (dlist.size() == 1) {
                    notifyItemChanged(dlist.get(0).getLocation() + 2);
                }
            }
        }
    }

    private class ImageSplitListener extends SimpleImageLoadingListener {
        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
            DetailImageData mData = mMapItems.get(imageUri);
            if (mData != null) {
                mData.onLoadingError();
                if (!onBind) {
                    notifyItemChanged(mData.getLocation());
                }
            }
        }

        @Override
        public void onDiskCacheComplete(String imageUri, File mfile, String type) {
            DetailImageData mData = mMapItems.get(imageUri);
            try {
                if (!type.equals("gif")) {
                    mData.setmFilePath(mfile.getAbsolutePath());
                    mTask.put(imageUri, new afterDownloadTask(mData, mfile));
                    mTask.get(imageUri).execute();
                    if (mData.getLocation() == 0) {
                        mItem.setBack_img(mfile.getAbsolutePath());
                        if (!onBind) {
                            new Handler(mContext.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    notifyItemChanged(0);
                                }
                            });
                        }
                    }
                } else {
                    mData.setType("gif");
                    mData.onLoadingComplete();
                    if (!onBind) {
                        new Handler(mContext.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                notifyItemChanged(0);
                            }
                        });
                    }
                }

            } catch (Exception e) {
                mData.onLoadingError();
                if (!onBind) {
                    notifyItemChanged(mData.getLocation());
                }
            }
        }
    }

    public int getCommentStartIndex() {
        return ilist.size() + 3;
    }

    public int getCommentSize() {
        return dlist.size();
    }

    public int getCommentIndex() {
        return ilist.size() + 5;
    }

    public int getChargeIndex() {
        return ilist.size() + 2;
    }

}
